package com.ljx.rabbit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljx.rabbit.domain.dto.GoodsPageDTO;
import com.ljx.rabbit.domain.po.Category;
import com.ljx.rabbit.domain.po.HeadGoods;
import com.ljx.rabbit.domain.po.Item;
import com.ljx.rabbit.domain.vo.*;
import com.ljx.rabbit.mapper.CategoryMapper;
import com.ljx.rabbit.mapper.ItemMapper;
import com.ljx.rabbit.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.rabbit.service.IItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-01-21
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    private final ItemMapper itemMapper;
    private final IItemService iItemService;


    @Override
    public List<CategoryHead> getCategoryHead() {
        List<Category> categorylist = list();
        List<Category> list1 = categorylist.stream().filter(category -> category.getLayer() == 1).collect(Collectors.toList());
        List<Category> list2 = categorylist.stream().filter(category -> category.getLayer() == 2).collect(Collectors.toList());

        List<CategoryHead> list = new ArrayList<>();

        LambdaQueryWrapper<Item> wrapper = new LambdaQueryWrapper<Item>().eq(Item::getIsHead, 1);
        List<Item> itemlist = itemMapper.selectList(wrapper);
        Map<Long, List<Item>> itemMap = itemlist.stream().collect(Collectors.groupingBy(Item::getCategoryId));
        //itemMap的key值是2级categoryId，需要修改为parentId
        //修改map的key值，让他为parentId
        for (Category category : list2) {
            if (itemMap.containsKey(category.getId())) {
                List<Item> remove = itemMap.remove(category.getId());
                if (itemMap.containsKey(category.getParentId()))
                    itemMap.get(category.getParentId()).addAll(remove);//就添加
                else
                    itemMap.put(category.getParentId(), remove);
            }
        }
        log.info("list1:{}", list1);
        log.info("list2:{}", list2);
        log.info("itemMap:{}", itemMap);
        //自己的想法
       /* for (Category item1 : list1) {
            CategoryHead categoryHead = new CategoryHead();
            BeanUtils.copyProperties(item1,categoryHead);
            for (Category item2 : list2) {
                CategoryHead categoryHead1 = new CategoryHead();
                if(item2.getParentId().equals(item1.getId())){//Long类型超过int范围使用equals
                    BeanUtils.copyProperties(item2,categoryHead1);
                    categoryHead.getChildren().add(categoryHead1);
                }
            }
            list.add(categoryHead);
        }*/
        //ai优化后,避免多次遍历 list2
        Map<Long, List<Category>> category2Map = list2.stream().collect(Collectors.groupingBy(Category::getParentId));
        for (Category item1 : list1) {
            CategoryHead categoryHead = new CategoryHead();
            BeanUtils.copyProperties(item1, categoryHead);
            List<Item> items = itemMap.get(item1.getId());
            if (items != null) {
                for (Item item : items) {
                    HeadGoods headGoods = new HeadGoods();
                    BeanUtils.copyProperties(item, headGoods);
                    categoryHead.getGoods().add(headGoods);
                }
            }
            List<Category> children = category2Map.get(item1.getId());
            if (children != null) {
                for (Category item2 : children) {
                    CategoryHead categoryHead1 = new CategoryHead();
                    BeanUtils.copyProperties(item2, categoryHead1);
                    categoryHead.getChildren().add(categoryHead1);
                }
            }
            list.add(categoryHead);
        }

        log.info("list:{}", list);
        return list;
    }

    @Override
    public List<HomeGoods> getHomeGoods(Integer limit) {
         List<Category> categorylist = list();
         //List<Category> list1 = categorylist.stream().filter(category -> category.getLayer() == 1).collect(Collectors.toList());
         List<Category> list2 = categorylist.stream().filter(category -> category.getLayer() == 2).collect(Collectors.toList());
        IPage<Category> page = new Page<>(1, limit);
        QueryWrapper<Category> eq = new QueryWrapper<>();
        eq.lambda().eq(Category::getLayer, 1);
        this.page(page, eq);

        List<Category> records = page.getRecords();
        log.info("records:{}", records);
        log.info("total:{}", page.getTotal());
        List<HomeGoods> homeGoodsList = new ArrayList<>();//最终返回

        //List<Long> ids = new ArrayList<>();
        if (records != null) {
            for (Category record : records) {
                HomeGoods homeGoods = new HomeGoods();
                BeanUtils.copyProperties(record, homeGoods);
                //ids.add(record.getId());
                homeGoodsList.add(homeGoods);
            }
        }

        /*//添加headGoods集合
        Map<Long, List<Long>> dadMapSon = new TreeMap<>();//父parentId，子id集合
        for (Category category : list2) {//获取映射关系
            if (dadMapSon.containsKey(category.getParentId())) {//存在，添加
                dadMapSon.get(category.getParentId()).add(category.getId());
            } else {//不存在，
                List<Long> list = new ArrayList<>();
                list.add(category.getId());
                dadMapSon.put(category.getParentId(), list);
            }
        }

        AtomicInteger i = new AtomicInteger(0);
        dadMapSon.forEach((k, v) -> {
            IPage<Item> page1 = new Page<>(1, 8);
            QueryWrapper<Item> qw = new QueryWrapper<>();
            qw.lambda().in(Item::getCategoryId, v).orderByDesc(Item::getRecommend);
            List<Item> items = itemMapper.selectList(page1, qw);
            log.info("items:{}", items);

            List<HeadGoods> list = new ArrayList<>();
            if (items != null) {
                for (Item item : items) {
                    HeadGoods goods = new HeadGoods();
                    BeanUtils.copyProperties(item, goods);
                    list.add(goods);
                }
            }
            if (i.get() < homeGoodsList.size())
                homeGoodsList.get(i.getAndIncrement()).setGoods(list);

        });*/
        //优化，更加统一
        Map<Long, List<Long>> dadMapSon = new LinkedHashMap<>();
        for (HomeGoods goods : homeGoodsList) {
            dadMapSon.put(goods.getId(),new ArrayList<Long>() );
        }
        log.info("dadMapSon:{}", dadMapSon);
        for (Category category : list2) {
            if (dadMapSon.containsKey(category.getParentId())) {
                dadMapSon.get(category.getParentId()).add(category.getId());
            }
        }
        log.info("dadMapSon:{}", dadMapSon);

        AtomicInteger i = new AtomicInteger(0);
        dadMapSon.forEach((k, v) -> {
            IPage<Item> page1 = new Page<>(1, 8);
            QueryWrapper<Item> qw = new QueryWrapper<>();
            qw.lambda().in(Item::getCategoryId, v).orderByDesc(Item::getRecommend);
            List<Item> items = itemMapper.selectList(page1, qw);
            log.info("items:{}", items);

            List<HeadGoods> list = new ArrayList<>();
            if (items != null) {
                for (Item item : items) {
                    HeadGoods goods = new HeadGoods();
                    BeanUtils.copyProperties(item, goods);
                    list.add(goods);
                }
            }
            if (i.get() < homeGoodsList.size())
                homeGoodsList.get(i.getAndIncrement()).setGoods(list);

        });

        log.info("homeGoodsList:{}", homeGoodsList);
        return homeGoodsList;
    }

    @Override
    public CategoryDetail getCategoryAndGoods(Long id) {
        QueryWrapper<Category> qw=new QueryWrapper<>();
        qw.lambda().eq(Category::getParentId,id);
        List<Category> categorylist = list(qw);//获取子类
        List<HomeGoods> homeGoodsList = new ArrayList<>();//最终返回
        for (Category category : categorylist) {
            HomeGoods goods = new HomeGoods();
            BeanUtils.copyProperties(category, goods);

            QueryWrapper<Item> qw1=new QueryWrapper<>();
            qw1.lambda().eq(Item::getCategoryId,category.getId());
            List<Item>  list=itemMapper.selectList(qw1);
           // List<HeadGoods> headGoodsList = new ArrayList<>();
            for (Item item : list) {
                HeadGoods goods1 = new HeadGoods();
                BeanUtils.copyProperties(item, goods1);
                //headGoodsList.add(goods1);
                goods.getGoods().add(goods1);
            }
            log.info("goods:{}", goods);
            homeGoodsList.add(goods);
        }
        CategoryDetail categoryDetail = new CategoryDetail();
        categoryDetail.setChildren(homeGoodsList);
        categoryDetail.setId(id);
        categoryDetail.setName(getById(id).getName());
        return categoryDetail;
    }

    @Override
    public CategoryFilter getCategoryFilter(Long id) {
        Category category = getById(id);
        CategoryFilter categoryFilter = new CategoryFilter();
        BeanUtils.copyProperties(category, categoryFilter);
        return categoryFilter;
    }

    @Override
    public GoodsPageVo getGoodsPage(GoodsPageDTO goodsPageDTO) {
        //由于商品太少，就把所有的商品返回回去，不分类
        Page<Item> page = new Page<>(goodsPageDTO.getPage(), goodsPageDTO.getPageSize());
        page.addOrder(OrderItem.desc(goodsPageDTO.covert(goodsPageDTO.getSortField())));

        IPage<Item> itemIPage = itemMapper.selectPage(page,null );
        //要分类，仅仅需要把二级分类id加进去
        if (itemIPage == null && itemIPage.getRecords() == null && itemIPage.getRecords().size() == 0)
            throw new RuntimeException("商品为空");
        GoodsPageVo pageVo = new GoodsPageVo();
        for (Item record : itemIPage.getRecords()) {
            HeadGoods goods = new HeadGoods();
            BeanUtils.copyProperties(record, goods);
            pageVo.getItems().add(goods);
        }
        pageVo.setCounts(itemIPage.getTotal());
        pageVo.setPage(goodsPageDTO.getPage());
        pageVo.setPages(itemIPage.getPages());
        pageVo.setPageSize(goodsPageDTO.getPageSize());

        return pageVo;
    }
}
